package com.phpxiu.app.view;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.phpxiu.app.adapter.UserFollowListAdapter;
import com.phpxiu.app.adapter.holder.UserFollowViewHolder;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.model.event.OnBlockEvent;
import com.phpxiu.app.model.list.UserAttentionContent;
import com.phpxiu.app.model.response.UserAttentionModel;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.pulltorefresh.PullToRefreshListView;
import com.phpxiu.app.pulltorefresh.PullToRefreshView;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.custom.ListEmptyView;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;

/**
 * 1.当进入查询界面进行操作时，返回本界面是否需要刷新数据，以便同步从返回界面操作产生的不同状态
 * Created by WuJinZhou on 2016/6/4.
 */
public class UserFollow extends UIBase implements View.OnClickListener,PullToRefreshView.OnRefreshListener2<ListView>,AdapterView.OnItemClickListener {
    private final static String TAG="UserAttention";
    public final static String EXTRA_PARAM_UID_KEY="extra_param_uid_key";
    private final static int HANDLE_REFRESH_COMPLETE=0x1;
    private String uid;
    private List<UserAttentionContent> attentions=new ArrayList<UserAttentionContent>();
    private PullToRefreshListView ptrRefreshView;
    private ListView mListView;
    private ListEmptyView emptyView;
    private UserFollowListAdapter mAdapter;
    private int mOpera= HttpConfig.REQUEST_OPERA_INIT;
    private int pageSize=15;//每页取15条记录
    private int currentAllRecords=0;//当前列表刷新时获取的后台记录条数
    private int pageIndex=1;//下一页序号,页数从1开始计数
    private OKHttpParam param;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        uid=getIntent().getStringExtra(EXTRA_PARAM_UID_KEY);
        if(uid==null||"".equals(uid)){
            finish();
            return;
        }
        setContentView(R.layout.user_follow);
        init();
    }

    /**
     * 初始化界面
     */
    private void init(){
        findViewById(R.id.top_bar_back_btn).setOnClickListener(this);
        ptrRefreshView=(PullToRefreshListView)findViewById(R.id.user_follow_pull_refresh_list);
        ptrRefreshView.setOnRefreshListener(this);
        mListView=ptrRefreshView.getRefreshableView();
        emptyView=new ListEmptyView(this);
        emptyView.setMsg(getString(R.string.list_empty_title));
        mListView.setEmptyView(emptyView);
        mListView.setOnItemClickListener(this);
        mListView.setDivider(null);
        boolean isMine=uid.equals(MySelfInfo.getInstance().getId());
        mAdapter=new UserFollowListAdapter(this,attentions,isMine);
        mListView.setAdapter(mAdapter);
        request(mOpera);
    }

    /**
     * 初始化请求
     */
    private void request(int opera){
        mOpera=opera;
        if(param==null){
            param=OKHttpParam.builder(false);
            param.put("uid",uid);
            param.put("pageSize",pageSize);
        }
        param.put("pageIndex",1);//刷新默认请求第一页，页序从1开始
        if(mOpera==HttpConfig.REQUEST_OPERA_LOAD){
            pageIndex=pageIndex==1?2:pageIndex;
            param.put("pageIndex",pageIndex);//如果加载更多请求，当前已加载的数据为第一页数据，那么加载更多的请求页序为第二页
        }
        OKHttp.post(HttpConfig.API_GET_USER_ATTENTION, param.jsonParam(), TAG, new OKHttpUIHandler(UserAttentionModel.class) {
            @Override
            public void onSuccess(Object model) {
                if(ptrRefreshView!=null){
                    ptrRefreshView.onRefreshComplete();
                }
                UserAttentionModel m = (UserAttentionModel) model;
                emptyView.loaded();
                KKYUtil.log("取到第"+param.get("pageIndex")+"页关注列表数据：" + m.getResponseStr());
                KKYUtil.log("总共"+m.getData().getTotalItem()+"条关注数据，当前取到的是第"+param.get("pageIndex")+"页"+m.getData().getUserlist().size()+"条关注数据");
                try {
                    if (mOpera == HttpConfig.REQUEST_OPERA_REFRESH || mOpera == HttpConfig.REQUEST_OPERA_INIT) {
                        currentAllRecords = m.getData().getTotalItem();
                        attentions.clear();
                        pageIndex = 1;
                    }
                    attentions.addAll(m.getData().getUserlist());
                    if(mOpera == HttpConfig.REQUEST_OPERA_LOAD){
                        if (currentAllRecords > 0 && attentions.size() > 0 && attentions.size() < currentAllRecords) {
                            pageIndex++;
                        }
                    }
                    KKYUtil.log("已请求到" + attentions.size()+"条关注数据");
                    mAdapter.notifyDataSetChanged();
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
                listEmpty(attentions.size() == 0);
            }

            @Override
            public void onErr(String errMsg) {
                listEmpty(attentions.size() == 0);
                if (ptrRefreshView != null) {
                    ptrRefreshView.onRefreshComplete();
                }
            }
        });
    }

    @Override
    public void handleMsg(Message msg) {
        switch (msg.what){
            case HANDLE_REFRESH_COMPLETE:
                if (ptrRefreshView != null) {
                    ptrRefreshView.onRefreshComplete();
                }
                break;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshView<ListView> refreshView) {
        request(HttpConfig.REQUEST_OPERA_REFRESH);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshView<ListView> refreshView) {
        if(attentions.size()!=0&&attentions.size()<currentAllRecords) {
            request(HttpConfig.REQUEST_OPERA_LOAD);
        }else{
            handler.sendEmptyMessage(HANDLE_REFRESH_COMPLETE);
        }
    }

    /**
     * 空列表,不加载更多
     */
    public void listEmpty(boolean isEmpty){
        if (ptrRefreshView != null) {
            if(isEmpty) {
                ptrRefreshView.setMode(PullToRefreshView.Mode.PULL_FROM_START);
            }else{
                ptrRefreshView.setMode(PullToRefreshView.Mode.BOTH);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_bar_back_btn:
                onBackPressed();
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(view.getTag()!=null&&view.getTag() instanceof UserFollowViewHolder){
            UserAttentionContent a=((UserFollowViewHolder)view.getTag()).getContent();
            KKYUtil.log(TAG, "点击了：" + a.getUid() + "@" + a.getNickname());
            Intent home=new Intent(this, UserHome.class);
            home.putExtra(UserHome.EXTRA_PARAM_KEY_UID,a.getUid());
            startActivity(home);
        }
    }

    /**
     * 拉黑事件
     */
    @Subscribe
    public void onBlackEvent(OnBlockEvent event){
        String id=event.getPeer();
        if(id==null||"".equals(id)){
            return;
        }
        for (UserAttentionContent a:attentions){
            if(id.equals(a.getUid())){
                attentions.remove(a);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        mAdapter.notifyDataSetChanged();
                    }
                });
                break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
